<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        li {
            list-style: none;
        }

        .menuBar {
            width: 200px;
            line-height: 36px;
            font-size: 13px;
            box-shadow: 0px 0px 6px 1px rgba(0, 0, 0, 0.2);
            border-radius: 4px;
            text-indent: 20px;
            position: fixed;
            left: -1000px;
            top: -1000px;
            display: none;
        }

        .menu li+li {
            border-top: 1px solid #ccc;
        }
    </style>
</head>

<body>
    <div class="menuBar">
        <ul class="menu">
            <li class="copy">复制</li>
            <li class="paste">粘贴</li>
            <li class="cut">剪切</li>
            <li class="refresh">刷新</li>
        </ul>
    </div>
</body>
<script>
    // 需求: 再页面中自定义菜单
    // (1) 禁用原本的菜单
    // (2) 自定义菜单

    var menuBar = document.querySelector(".menuBar");

    document.addEventListener("contextmenu", contextmenuHandler);

    document.addEventListener("mousedown", mousedownHandler)
    menuBar.addEventListener("mousedown", stopPropagationHandler)

    menuBar.addEventListener("click", clickHandler)

    function contextmenuHandler(e) {
        console.log("鼠标右键菜单");

        // 先阻止默认菜单
        if (e.preventDefault) {
            e.preventDefault();
        } else {
            e.returnValue = false;
        }

        // 显示自己的菜单
        var x = e.clientX;
        var y = e.clientY;

        menuBar.style.display = "block";
        menuBar.style.left = x + "px";
        menuBar.style.top = y + "px";

    }

    // 点击文档任意位置隐藏菜单 => 问题: 在菜单上按下,也会冒泡到document => 触发隐藏 
    // 优化处理: 点击菜单时, 菜单不隐藏
    function mousedownHandler() {
        console.log("文档任意位置按下");
        menuBar.style.display = "none";
    }

    // 点击点击菜单时, 菜单不隐藏 => 阻止事件冒泡处理
    function stopPropagationHandler(e) {
        if (e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.cancelBubble = true;
        }
    }

    // 点击触发 复制 粘贴 剪切 刷新功能  => 配合额外的JS代码
    function clickHandler(e) {
        var target = e.target;
        if (target.className == "copy") {
            console.log("点击复制,触发复制功能");
            menuBar.style.display = "none";
        } else if (target.className == "paste") {
            console.log("点击复制,触发粘贴功能");
            menuBar.style.display = "none";
        } else if (target.className == "cut") {
            console.log("点击复制,触发剪切功能");
            menuBar.style.display = "none";
        } else if (target.className == "refresh") {
            console.log("点击复制,触发刷新功能");
            menuBar.style.display = "none";
            location.reload();
        }
    }





</script>

</html>